<template>
    <a-modal
        :title="isEdit ? '编辑' : '新增'"
        :open="props.open"
        @update:open="emit('update:open', $event)"
        @ok="handleSubmit"
        @cancel="handleCancel"
        :confirm-loading="confirmLoading"
    >
        <a-form ref="formRef" :model="formModel" :rules="rules" layout="vertical">
            <!-- 标题 -->
            <a-form-item label="标题" name="title">
                <a-input v-model:value="formModel.title" placeholder="请输入文章标题" allow-clear />
            </a-form-item>

            <!-- 作者 -->
            <a-form-item label="作者" name="author">
                <a-input v-model:value="formModel.author" placeholder="请输入作者名" allow-clear />
            </a-form-item>

            <!-- 分类 -->
            <a-form-item label="分类" name="categoryId">
                <a-select v-model:value="formModel.categoryId" placeholder="请选择分类" allow-clear>
                    <a-select-option v-for="item in categoryList.data" :key="item.id" :value="item.id">
                        {{ item.name }}
                    </a-select-option>
                </a-select>
            </a-form-item>

            <!-- 封面图（URL） -->
            <a-form-item label="封面图 URL" name="coverImage">
                <a-input v-model:value="formModel.coverImage" placeholder="请输入封面图片 URL" allow-clear />
                <div class="text-sm text-gray-400">
                    图片存放于 client\pc\dist\image，链接为：http://localhost:7001/image/完整文件名
                </div>
            </a-form-item>

            <!-- 摘要 -->
            <a-form-item label="摘要" name="excerpt">
                <a-textarea
                    v-model:value="formModel.excerpt"
                    placeholder="请输入文章摘要"
                    :auto-size="{ minRows: 2, maxRows: 4 }"
                    allow-clear
                />
            </a-form-item>

            <!-- 内容（富文本占位，后续可替换为 wangEditor / tinymce） -->
            <a-form-item label="内容" name="content">
                <a-textarea
                    v-model:value="formModel.content"
                    placeholder="请输入文章内容"
                    :auto-size="{ minRows: 8, maxRows: 20 }"
                    allow-clear
                />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup lang="ts">
import { useRequest } from "alova/client";
import type { FormProps } from "ant-design-vue";

import type { ArticleEntity } from "@/api/globals";

const props = defineProps<{
    open: boolean;
    record?: ArticleEntity | null; // 编辑时传入，新增时为 null 或 undefined
}>();

const emit = defineEmits<{
    (e: "update:open", value: boolean): void;
    (e: "success"): void;
}>();

// 表单引用
const formRef = ref();

// 表单数据
const formModel = reactive<Partial<ArticleEntity>>({
    title: "",
    excerpt: "",
    content: "",
    author: "",
    coverImage: "", // url
    categoryId: "" as unknown as number
});

// 是否为编辑模式
const isEdit = computed(() => !!props.record?.id);

// 确认加载状态
const confirmLoading = ref(false);

// 表单验证规则
const rules: FormProps["rules"] = {
    title: [{ required: true, message: "请输入标题", whitespace: true }],
    author: [{ required: true, message: "请输入作者", whitespace: true }],
    excerpt: [{ required: true, message: "请输入摘要", whitespace: true }],
    content: [{ required: true, message: "请输入内容", whitespace: true }],
    categoryId: [{ required: true, message: "请选择分类" }]
};

// 监听 open 变化，初始化表单
watch(
    () => [props.open, props.record],
    ([isOpen, record]) => {
        if (isOpen) {
            if (record) {
                // 编辑：回填数据
                Object.keys(formModel).forEach(key => {
                    (formModel as any)[key] = (props.record as any)[key];
                });
            } else {
                // 新增：清空表单
                Object.keys(formModel).forEach(key => {
                    (formModel as any)[key] = void 0;
                });
                formRef.value?.clearValidate(); // 重置表单验证状态
            }
        }
    },
    { immediate: true }
);
// 提交表单
const handleSubmit = async () => {
    try {
        const values = await formRef.value.validateFields();
        confirmLoading.value = true;

        if (isEdit.value) {
            // 调用编辑 API
            await Apis.ArticleAdmin.update({
                pathParams: { id: props.record!.id },
                data: values
            });
        } else {
            // 调用新增 API
            await Apis.ArticleAdmin.create({ data: values });
        }

        emit("success"); // 通知父组件刷新
        handleCancel(); // 关闭弹窗
    } catch (error) {
        console.error("表单提交失败:", error);
    } finally {
        confirmLoading.value = false;
    }
};

// 取消/关闭
const handleCancel = () => {
    emit("update:open", false);
};

const { data: categoryList } = useRequest(() => Apis.CategoryAdmin.list());
</script>
